//
//  PicCell.m
//  Connotation
//
//  Created by LZXuan on 15-4-7.
//  Copyright (c) 2015年 LZXuan. All rights reserved.
//

#import "PicCell.h"
#import "UIImageView+WebCache.h"
#import "LZXHttpRequest.h"
#import "CommentViewController.h"
/** 弹出提醒视图 */
#define AlertViewShow(s)  { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:s  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show];}

@implementation PicCell
{
    LZXHttpRequest *_httpRequest;
}
- (void)awakeFromNib
{
    // Initialization code
    //代码初始化方法 在这里写
    _httpRequest = [[LZXHttpRequest alloc] init];
    
    [self.likeButton setTitleColor:[UIColor redColor] forState:UIControlStateDisabled];
    self.SaveImageButton.frame=CGRectMake(0, 0, 0, 0);
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)showDataWithModel:(PicModel *)model category:(NSString *)category{
   
    //每次填充cell  更新 category  wid
    self.category = category;
    self.model = model;
    
    //转换
    self.dateLabel.text = [LZXHelper dateStringFromNumberTimer:model.update_time];
    
    CGRect bodyFrame = self.dateLabel.frame;
    
    if (model.wbody) {//区分 段子/趣图/美女 -> model.wbody 美女接口数据没有
        //内容字符串
        self.bodyLabel.text = model.wbody;
        self.bodyLabel.numberOfLines = 0;
        self.bodyLabel.lineBreakMode = NSLineBreakByCharWrapping;
        //根据内容字符串动态计算高度
        //先获取 frame
        bodyFrame = self.bodyLabel.frame;
        bodyFrame.size.height = [LZXHelper textHeightFromTextString:model.wbody width:280 fontSize:14];
        
    }
    //重新设置高度
    self.bodyLabel.frame = bodyFrame;
    
    CGRect imageFrame = bodyFrame;
    if (model.wpic_middle) { // model.wpic_middle段子数据中没有
        //有图片 动态计算 (区分 段子/趣图/美女界面)
        //图片
        //异步下载
        [self.picImageView sd_setImageWithURL:[NSURL URLWithString:model.wpic_middle] placeholderImage:[UIImage imageNamed: @"card_bg"]];
        self.picImageView.userInteractionEnabled=YES;
        imageFrame = self.picImageView.frame;
        //改y 和高度
        imageFrame.origin.y = bodyFrame.origin.y+bodyFrame.size.height+5;
        imageFrame.size.height = [model.wpic_m_height doubleValue]*280/[model.wpic_m_width doubleValue];
        //重新设置高度
        self.picImageView.frame = imageFrame;
        self.SaveImageButton.frame=imageFrame;
    }
    
    
    CGRect buttonFrame1 = self.likeButton.frame;
    buttonFrame1.origin.y = imageFrame.origin.y+imageFrame.size.height+10;
    self.likeButton.frame = buttonFrame1;
    
    
    CGRect buttonFrame2 = self.commentButton.frame;
    buttonFrame2.origin.y = buttonFrame1.origin.y;
    self.commentButton.frame = buttonFrame2;
    NSString *title = [NSString stringWithFormat:@"赞:%ld",[model.likes integerValue]];
    
    //读本地有没有保存点赞数据 如果点过了那么肯定有保存 有保存禁用它
    NSString *zanStr = [[NSUserDefaults standardUserDefaults] objectForKey:[self.category stringByAppendingString:self.model.wid]];
    
    if (zanStr) {
        //self.likeButton.enabled = NO;
    }else {
        self.likeButton.enabled = YES;
    }
    
    [self.likeButton setTitle:title forState:UIControlStateNormal];
    [self.commentButton setTitle:[NSString stringWithFormat:@"评论:%@",model.comments]forState:UIControlStateNormal];
}


- (void)dealloc {
    self.myblock = nil;
    
    [_category release];
    [_model release];
    
    [_httpRequest release];
    [_dateLabel release];
    [_bodyLabel release];
    [_picImageView release];
    [_likeButton release];
    [_commentButton release];
    [_SaveImageButton release];
    [super dealloc];
}
- (IBAction)likesClick:(id)sender {
    //立即 保存到本地 赞数 +1
    NSInteger count = [self.model.likes integerValue]+1;
    //把赞数 作为值 key->weibo_jokes30101
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld",count] forKey:[self.category stringByAppendingString:self.model.wid]];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //修改model 的赞数据
    self.model.likes = [NSString stringWithFormat:@"%ld",count];
    
    UIButton *button = (UIButton *)sender;
    //button.enabled = NO;
    
    [button setTitle:[NSString stringWithFormat:@"赞:%ld",count] forState:UIControlStateNormal];

        //得到 category  wid
    //参数 拼接
    //type=like&category=%@&fid=%@
    NSString *paramsStr = [NSString stringWithFormat:@"type=like&category=%@&fid=%@",self.category,self.model.wid];
    
#if 1
    [_httpRequest postRequestWithUrl:kZanUrl params:paramsStr success:^(LZXHttpRequest *request) {
        //点赞成功 服务端 返回一个0
    } fail:^(NSError *error) {
        NSLog(@"点赞失败");
    }];

#else
    for (NSInteger i = 0; i < 1000; i++) {
        [_httpRequest postRequestWithUrl:kZanUrl params:paramsStr success:^(LZXHttpRequest *request) {
            //点赞成功 服务端 返回一个0
            //NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.downloadData options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"dict:%@",dict);
        } fail:^(NSError *error) {
            NSLog(@"点赞失败");
        }];
    }
#endif
    
    
}

- (IBAction)commentClick:(id)sender {
    NSString *url = [NSString stringWithFormat:kCommentsUrl,self.model.wid,self.category];
    //委托 视图控制器界面进行 push 跳转
    if (self.myblock) {
        //回调block  block中 应该写界面跳转
        self.myblock(url);
    }
}
- (IBAction)saveClick:(id)sender {
    self.SaveImageButton.userInteractionEnabled=NO;
    //GCD串行队列异步任务
    dispatch_queue_t p =dispatch_queue_create("add", DISPATCH_QUEUE_SERIAL);
    dispatch_async(p, ^{
        
    /*保存静态图*/
//     UIImageWriteToSavedPhotosAlbum(self.picImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    /*保存动态图*/
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    NSData *data = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString:self.model.wpic_middle]];
    [library writeImageDataToSavedPhotosAlbum:data
                                     metadata:nil
                              completionBlock:^(NSURL *assetURL, NSError *error) {
                                  if (error) {
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          AlertViewShow(@"保存失败");
                                      });
                                      
                                  } else {
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          AlertViewShow(@"保存成功");
                                      });
                                      
                                  }
                              }];
        
        });
    self.SaveImageButton.userInteractionEnabled=YES;
}
// 指定回调方法

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

{
    
    NSString *msg = nil ;
    
    if(error != NULL){
        
        msg = @"保存图片失败" ;
        
        
    }else{
        
        msg = @"保存图片成功" ;
       
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
                          
                                                    message:msg
                          
                                                   delegate:self
                          
                                          cancelButtonTitle:@"确定"
                          
                                          otherButtonTitles:nil];
    
    [alert show];
    self.SaveImageButton.userInteractionEnabled=YES;
}
@end
